package com.ptmall.app.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.facebook.stetho.common.LogUtil;
import com.google.gson.Gson;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.AddressBean;
import com.ptmall.app.bean.HomePageArea;
import com.ptmall.app.bean.PageData;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.utils.LocationUtil;
import com.ptmall.app.view.AddressPickTask;
import com.ptmall.app.view.TitleBarView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;

public class AddAddressActivity extends BaseMvpActivity {

    TitleBarView titlebar;

    AddressBean mAddressBean;

    CheckBox moren;
    TextView del_address,area,tv_xiaoqu;
    EditText address,phone,name;

    double latitude,longitude;

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    private AlertDialog.Builder builder;

    List<HomePageArea> homePageAreasList = new ArrayList<>();
    List<String> xiaoquList = new ArrayList<>();

    private String xiaoquId = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_addaddress);
        initLocation();
    }

    @Override
    public void initViews() {

        titlebar = (TitleBarView) findViewById(R.id.titlebar);

        moren = (CheckBox) findViewById(R.id.moren);
        tv_xiaoqu = (TextView) findViewById(R.id.xiaoqu);
        name = (EditText) findViewById(R.id.name);
        phone = (EditText) findViewById(R.id.phone);
        address = (EditText) findViewById(R.id.address);

        del_address = (TextView) findViewById(R.id.del_address);
        area = (TextView) findViewById(R.id.area);

        del_address.setVisibility(View.GONE);

        if(getIntent().getSerializableExtra("bean") != null){
            titlebar.setText("编辑地址");
            mAddressBean = (AddressBean) getIntent().getSerializableExtra("bean");
            setAddress();
            del_address.setVisibility(View.VISIBLE);
        }

        del_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deladdress();
            }
        });
        titlebar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {
//                if(!TextUtils.isEmpty(name.getText().toString())&&!TextUtils.isEmpty(phone.getText().toString())&&
//                        !TextUtils.isEmpty(area.getText().toString())&&!TextUtils.isEmpty(address.getText().toString())){
//                    showMsg("请填写信息");
//                    return;
//                }
                if(mAddressBean == null){
                    addaddress();
                }else {
                    editaddress();
                }
            }
        });

        area.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onAddressPicker(view);
            }
        });

        area.setText("山东省 临沂市 兰山区");
        getHomePageAreaList("临沂市","兰山区");

    }
    public void onAddressPicker(View view) {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {
                showMsg("数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                if (county == null) {
//                    showMsg(province.getAreaName() + city.getAreaName());
                } else {
                    getHomePageAreaList(city.getAreaName(),county.getAreaName());
                    tv_xiaoqu.setText("选择小区");
                    xiaoquId = "";
                    area.setText(province.getAreaName() + city.getAreaName() + county.getAreaName());
//                    showMsg(province.getAreaName() + city.getAreaName() + county.getAreaName());
                }
            }
        });
        task.execute("山东省", "临沂市", "兰山区");
    }
    private void setAddress(){
        name.setText(mAddressBean.trueName);
        phone.setText(mAddressBean.tel);
        area.setText(mAddressBean.area);
        address.setText(mAddressBean.address);
        tv_xiaoqu.setText(mAddressBean.name);
        xiaoquId = mAddressBean.quId;
    }

    @Override
    public void initEvents() {
        tv_xiaoqu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] array = (String[])xiaoquList.toArray(new String[xiaoquList.size()]);
                builder = new AlertDialog.Builder(getActivity())
                        .setTitle("小区列表")
                        .setItems(array, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                tv_xiaoqu.setText(homePageAreasList.get(i).name);
                                xiaoquId = homePageAreasList.get(i).quId;
                            }
                        });
                builder.create().show();
            }
        });
    }

    private void addaddress(){
        if(TextUtils.isEmpty(name.getText().toString())||
                TextUtils.isEmpty(phone.getText().toString())||
                TextUtils.isEmpty(area.getText().toString())||
                TextUtils.isEmpty(address.getText().toString())||
                TextUtils.isEmpty(xiaoquId)){
            showMsg("请填写信息");
            return;
        }
        Map<String,String> map = new HashMap<>();
        map.put("trueName",name.getText().toString());
        map.put("tel",phone.getText().toString());
        map.put("area",area.getText().toString());
        map.put("address",address.getText().toString());
        map.put("quId",xiaoquId);
        map.put("is_default",(moren.isChecked()?1:2)+"");

        apiDataRepository.addAddress(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("添加地址成功");
                finish();
            }
        });
    }


    private void editaddress(){
        Map<String,String> map = new HashMap<>();
        map.put("addressId",mAddressBean.addressId);
        map.put("trueName",name.getText().toString());
        map.put("tel",phone.getText().toString());
        map.put("area",area.getText().toString());
        map.put("address",address.getText().toString());
        map.put("quId",xiaoquId);
        map.put("is_default",(moren.isChecked()?1:2)+"");

        apiDataRepository.editAddress(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("添加地址成功");
                finish();
            }
        });
    }


    private void deladdress(){
        Map<String,String> map = new HashMap<>();
        map.put("addressId",mAddressBean.addressId);

        apiDataRepository.delAddress(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("删除地址成功");
                finish();
            }
        });
    }


    private void initLocation(){
        requestRuntimePermisssions(new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionListener() {
            @Override
            public void onGranted() {
                LocationUtil.setCurrentAddress(new LocationUtil.currentAddress() {
                    @Override
                    public void getAddress(BDLocation location) {
                        if(location==null){
                            showMsg("定位失败，请打开GPS定位功能");
                            LogUtil.d("xucc","定位失败222");
                            return;
                        }
                        Log.d("xucc",new Gson().toJson(location));
                        longitude=location.getLongitude();
                        latitude=location.getLatitude();
                        getHomePageAreaList("临沂市","兰山区");
                    }
                },getContext(),true);
            }

            @Override
            public void onDenied(List<String> deniedList) {
                showMsg("定位权限获取失败");
            }
        });
    }

    private void getHomePageAreaList(String city,String qu){
        Map<String,String> map = new HashMap<>();
        map.put("lat",latitude+"");
        map.put("lng",longitude+"");
        map.put("city",city+"");
        map.put("xianqu",qu+"");
        apiDataRepository.homePageAreaList(map, new ApiNetResponse<PageData<HomePageArea>>(getContext()) {
            @Override
            public void onSuccess(PageData<HomePageArea> data) {
                xiaoquList.clear();
                homePageAreasList.clear();
                homePageAreasList.addAll(data.getData());
                for(HomePageArea homePageArea:data.getData()){
                    xiaoquList.add(homePageArea.name);
                }
            }
        });
    }

}
